<script setup>
import { ref } from 'vue'
import { store } from '../../store/avgstore.js'

const props = defineProps(['chapterName'])
const dir = '/exilium/avg/' + store.cptId + '/'

const list = ref([])
const p1 = fetch(dir + 'roadmap.json')
    .then(response => response.json())
const p2 = fetch(dir + 'detail.json')
    .then(response => response.json())
Promise.all([p1, p2]).then(jsons => {
  const json = jsons[0]
  addIntros(json, Object.values(jsons[1]))
  list.value = json
})

function addIntros(base, pool) {
  for (const pair of base) {
    const match = pool.findLast(item => item.num == pair[0])
    pair.push(match?.desc || '')
  }
}

function viewAvg(event) {
  const target = event.currentTarget
  if (target.classList.contains('no-avg')) {
    return
  }
  const avgNo = target.getAttribute('num')
  fetch(dir + avgNo + '.json')
      .then(response => {
        if (response.status == 404) {
          target.lastElementChild.textContent += '（本关无AVG剧情）'
          target.classList.add('no-avg')
        } else {
          store.avgNo = avgNo
          store.avgName = target.firstElementChild.textContent
          store.viewIdx = 2;
        }
      })
}

function returnToChapters() {
  store.viewIdx = 0
}
</script>

<template>
  <section>
  <nav>
    <button @click="returnToChapters">返回</button>
  </nav>
  <h1>{{ props.chapterName }}</h1>
  <div id="stage-list">
    <table>
      <tr v-for="pair of list" :num="pair[0]" @click="viewAvg">
        <td>{{ pair[0] }} {{ pair[1] }}</td>
        <td>{{ pair[2] }}</td>
      </tr>
    </table>
    <img :src="dir + 'map.png'">
  </div>
  </section>
</template>

<style scoped>
#stage-list {
  align-items: start;
  display: flex;
  flex-wrap: wrap;
}
table {
  border-spacing: 0;
}
tr {
  cursor: pointer;
}
tr.no-avg {
  cursor: default;
}
td {
  border-bottom: 1px solid;
}
tr:last-child td {
  border-bottom: none;
}
td:first-child {
  color: hsl(160, 100%, 37%);
  font-weight: bold;
  width: 10em;
}
tr.no-avg td:first-child {
  color: unset;
}
img {
  max-width: 100%;
  width: 300px;
}
</style>